﻿using Corina.Commands;
using Corina.Common;
using Corina.Datamodel.DataObject;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Input;

namespace Corina.Cydee.Apphub.Viewmodels
{
    public class DeviceMessageViewmodel : ViewmodelBase
    {
        #region Constructor
        public DeviceMessageViewmodel()
        {
            DeviceMeasureClient.GetAllDeviceMessageCompleted += GetAllDeviceMessageCompleted;
            DeviceClient.GetDeviceKindItemsCompleted += GetDeviceKindItemsCompleted;
            DeviceMeasureClient.RemoveDeviceMessageCompleted += RemoveDeviceMessageCompleted;
            DeviceMeasureClient.ResolveDeviceMessageCompleted += ResolveDeviceMessageCompleted;
            DeviceMeasureClient.GetDeviceMessageInfoCompleted+=GetDeviceMessageInfoCompleted;
            LoadRelatedData();
            if(DataContext.IsValid)
            {
                LoadData();
            }
        }

        private void GetDeviceMessageInfoCompleted(object sender, DataService.GetDeviceMessageInfoCompletedEventArgs e)
        {
            if(e.Error == null)
            {
                DetailEntity = e.Result.Entities.OfType<DeviceMessageInfo>().FirstOrDefault();
                ShowDetail = true;
            }
        }
        #endregion

        #region Methods
        private void ResolveDeviceMessageCompleted(object sender, DataService.ResolveDeviceMessageCompletedEventArgs e)
        {
            if(ShowDetail)
            {
                DetailEntity = null;
                ShowDetail = false;
            }
            LoadData();
        }

        private void RemoveDeviceMessageCompleted(object sender, DataService.RemoveDeviceMessageCompletedEventArgs e)
        {
            LoadData();
        }

        private void GetDeviceKindItemsCompleted(object sender, DataService.GetDeviceKindItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                DeviceKindCollection = new ObservableCollection<DeviceKindInfo>(e.Result.Entities.OfType<DeviceKindInfo>());
            }
        }

        private void GetAllDeviceMessageCompleted(object sender, DataService.GetAllDeviceMessageCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                var items = (from t in e.Result.DataObjects
                             select new
                             {
                                 ItemIndex = t["ROW_NUMBER"],
                                 Id = t["Id"],
                                 DeviceSn = (string)t["DeviceSn"],
                                 Kind = (string)t["Kind"],
                                 Content = ((string)t["Content"]).TrimStart(' '),
                                 ProofValue = (string)t["ProofValue"],
                                 Abnormal = CheckProofValue((string)t["DeviceSn"], (string)t["ProofValue"]),
                                 UserName = t["UserName"],
                                 TransType = (TransTypeValue)Convert.ToInt32(t["TransType"]),
                                 ReceivedTime = Convert.ToDateTime(t["RecievedTime"]),
                                 IsAnalysed = Convert.ToBoolean(t["IsAnalysed"]),
                                 MobileOrIP = t["MobileOrIP"],
                                 MeasureTime = t["MeasureTime"]
                             });
                ItemsCollection = new ObservableCollection<object>(items);
                ItemsCount = e.Result.TotalCount;
            }
            IsBusy = false;
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            DeviceMeasureClient.GetAllDeviceMessageAsync(Account, Password, DeviceSn, KindId, Keywords, SearchAll, Index, 20);
        }

        private void LoadRelatedData()
        {
            DeviceClient.GetDeviceKindItemsAsync();
        }

        private bool CheckProofValue(string deviceSn,string proofValue)
        {
            if(string.IsNullOrEmpty(proofValue))
            {
                return false;
            }
            int index = Convert.ToInt32(proofValue.Substring(0, 1));
            string value = deviceSn.Substring((index - 1) * 3, 3);
            return value != proofValue.Substring(1, 3);
        }
        #endregion

        #region Collection
        private ObservableCollection<object> _itemsCollection;
        public ObservableCollection<object> ItemsCollection
        {
            get { return _itemsCollection; }
            set
            {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
            }
        }

        private ObservableCollection<DeviceKindInfo> _deviceKindCollection;
        public ObservableCollection<DeviceKindInfo> DeviceKindCollection
        {
            get { return _deviceKindCollection; }
            set
            {
                _deviceKindCollection = value;
                RaisePropertyChanged(() => DeviceKindCollection);
            }
        }
        #endregion

        #region Condition
        private string _deviceSn = string.Empty;
        public string DeviceSn
        {
            get { return _deviceSn; }
            set
            {
                _deviceSn = value;
                RaisePropertyChanged(() => DeviceSn);
            }
        }

        private string _keywords = string.Empty;
        public string Keywords
        {
            get { return _keywords; }
            set
            {
                _keywords = value;
                RaisePropertyChanged(() => Keywords);
            }
        }

        private int _kindId = 0;
        public int KindId
        {
            get { return _kindId; }
            set
            {
                _kindId = value;
                RaisePropertyChanged(() => KindId);
            }
        }

        private bool _searchAll = false;
        public bool SearchAll
        {
            get { return _searchAll; }
            set
            {
                _searchAll = value;
                RaisePropertyChanged(() => SearchAll);
                Index = 1;
                LoadData();
            }
        }

        private DeviceKindInfo _selectedDeviceKind;
        public DeviceKindInfo SelectedDeviceKind
        {
            get
            {
                return _selectedDeviceKind;
            }
            set
            {
                _selectedDeviceKind = value;
                RaisePropertyChanged(() => SelectedDeviceKind);
                KindId = SelectedDeviceKind == null ? 0 : SelectedDeviceKind.Id;
            }
        }
        #endregion

        #region Properties
        private bool _showDetail = false;
        public bool ShowDetail
        {
            get { return _showDetail; }
            set
            {
                _showDetail = value;
                RaisePropertyChanged(() => ShowDetail);
            }
        }

        private DeviceMessageInfo _detailEntity = new DeviceMessageInfo();
        public DeviceMessageInfo DetailEntity
        {
            get { return _detailEntity; }
            set
            {
                _detailEntity = value;
                RaisePropertyChanged(() => DetailEntity);
            }
        }
        #endregion

        #region Commands
        public ICommand LoadCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        Index = 1;
                        LoadData();
                    }
                };
            }
        }

        public ICommand ResolveCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);

                    DeviceMeasureClient.ResolveDeviceMessageAsync(Account, Password, id);

                });
            }
        }

        public ICommand RemoveCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    if (ShowConfirm(Language.LanguageKeys.IDS_DELETE_CONFIRM) == MessageBoxResult.OK)
                    {
                        DeviceMeasureClient.RemoveDeviceMessageAsync(Account, Password, id);
                    }
                });
            }
        }

        public ICommand ShowDetailCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    DeviceMeasureClient.GetDeviceMessageInfoAsync(Account, Password, id);
                });
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        DetailEntity = null;
                        ShowDetail = false;
                    }
                };
            }
        }
        #endregion
    }
}
